#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <sys/shm.h>
#include <cerrno>
#include <cstring>
using namespace std;

const char *PATH = "/home/lw/code/4-15";
const int PROJ_ID = 0x1234;
const int DEFAULT_SIZE = 4096;

string ToHEX(key_t key)
{
    char buff[1024];
    snprintf(buff, sizeof(buff) - 1, "%#x", key);
    return buff;
}

key_t GetKeyOrDie()
{
    key_t key = ftok(PATH, PROJ_ID);
    if (key < 0)
    {
        cout << "ftok error, errno : " << errno << ", error string : " << strerror(errno) << endl;
        exit(1);
    }
    return key;
}

int CreateShmOrDie(key_t key, size_t size)
{
    int shmid = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid < 0)
    {
        cout << "shmget error, errno : " << errno << ", error string : " << strerror(errno) << endl;
        exit(1);
    }
    return shmid;
}

int GetShm(key_t key, size_t size)
{
    int shmid = shmget(key, size, IPC_CREAT);
    if (shmid < 0)
    {
        cout << "shmget error, errno : " << errno << ", error string : " << strerror(errno) << endl;
        exit(1);
    }
    return shmid;
}

void DebugShm(int shmid)
{
    struct shmid_ds shmds;
    int ret = shmctl(shmid, IPC_STAT, &shmds);
    if (ret < 0)
    {
        cout << "debug shm error, errno : " << errno << ", error string : " << strerror(errno) << endl;
    }
    cout << "shmid : " << shmid << endl;
    cout << "shm size : " << shmds.shm_segsz << endl;
    cout << "shm nattch : " << shmds.shm_nattch << endl;
    cout << "shm key : " << ToHEX(shmds.shm_perm.__key) << endl;
}

void DestroyShm(int shmid)
{
    int ret = shmctl(shmid, IPC_RMID, nullptr);
    if (ret < 0)
    {
        cout << "destroy shm error, errno : " << errno << ", error string : " << strerror(errno) << endl;
    }
}

void *AttachShm(int shmid)
{
    void *address = shmat(shmid, nullptr, 0);
    if ((long long)address < 0)
    {
        cout << "shmat error, errno : " << errno << ", error string : " << strerror(errno) << endl;
        exit(1);
    }
    return address;
}

void DetachShm(void *address)
{
    int ret = shmdt(address);
    if (ret < 0)
    {
        cout << "shmdt error, errno : " << errno << ", error string : " << strerror(errno) << endl;
    }
}